#include <go32.h>
#include <sys/farptr.h>
#include <sys/nearptr.h>
#include <pc.h>

#include "utypes.h"
#include "timer.h"
#include <dos.h>

#include <stdio.h>

#include "ints.h"

void t0_isr(void);
int mil_tick;
int sec_tick;

/** Program timer (0,1,2) with mode
 */
void timer_init(int timer, int mode)
{
	outportb(TIMER_CTRL,(timer<<6)|mode);
	outportb(SPEAKER_CTRL,inportb(SPEAKER_CTRL)|TIMER2_ENABLE);
}

/** Load timer (0,1,2) with value
 */
void timer_load(int timer, int value)
{
	outportb(TIMER_0|timer, LSB(value));
	outportb(TIMER_0|timer, MSB(value));
}

/** Wait mili miliseconds, indirectly counting T0 interrupts
*/
void mili_sleep(int mili)
{
	//delay(mili);
	
	int val = TIMER_CLK / 1000.0;
	
	timer_load(0, val);
	mil_tick = 0;
	
	_go32_dpmi_seginfo old_irq;
	install_asm_irq_handler(T0_IRQ, t0_isr, &old_irq);
	
	while(mil_tick < mili) {}
	
	reinstall_asm_irq_handler(T0_IRQ, &old_irq);
}

/** wait secs seconds, indirectly counting T0 interrupts
 */
void sec_sleep(int secs)
{
	//delay(secs*1000);
	
	mili_sleep(secs*1000);
}
